<template>
  <div class="flex_cm container" style="height: 100%">
    <search
      :form_data="header_list"
      @changeIsShow="
        (e) => {
          header_list[e].isShow = !header_list[e].isShow;
          header_list[e].value = header_list[e].type == 'input_number' ? ['', ''] : '';
        }
      "
      @search="search_key"
      @reset="
        header_list.forEach((item) => {
          item.value = '';
        }),
          search_key()
      "
    ></search>
    <div class="p_0_10 bg_fff flex1">
      <div class="flex_js p_10_0">
        <div>服务企业</div>
        <div class="flex">
          <el-button type="primary" @click="show_box = true">新增</el-button>
          <setTable
            :data="header_list"
            :height_size="height_size"
            @changeShowTable="
              (e) => {
                header_list[e].showTable = !header_list[e].showTable;
              }
            "
            @resetTableSet="
              () => {
                header_list.forEach((item) => {
                  item.showTable = true;
                });
              }
            "
            @changeHeightSize="
              (e) => {
                height_size = e;
              }
            "
          ></setTable>
        </div>
      </div>
      <el-table
        style="text-align: center"
        :data="table_list"
        :max-height="max_height"
        border
        :loading="loading"
        :default-sort="{ prop: 'name', order: 'descending' }"
        :row-style="{
          height: height_size == 1 ? '58px' : height_size == 2 ? '48px' : '38px',
        }"
        :cell-style="{
          padding: height_size == 3 ? '0' : '',
        }"
      >
        <el-table-column type="index" label="序号" width="80px"></el-table-column>
        <el-table-column
          label="企业名称"
          prop="name"
          key="企业名称"
          sortable
          v-if="header_list[0].showTable"
        ></el-table-column>

        <el-table-column label="操作" width="300px">
          <template #default="scope">
            <el-button
              @click="
                (serviceEnterpriseId = scope.row.id),
                  get_node_file_list(serviceEnterpriseId);
              "
              >节点资料配置</el-button
            >
            <el-button
              @click="
                (serviceEnterpriseId = scope.row.id),
                  get_node_file_template_list(serviceEnterpriseId);
              "
              >资料模板配置</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-drawer
      v-model="show_box"
      direction="rtl"
      size="50%"
      destroy-on-close
      @close="resetForm(addServiseEnterprise)"
      :close-on-click-modal="false"
    >
      <template #title
        ><h4 v-if="add_form_data.id == ''">新增</h4>
        <h4 v-else>编辑</h4></template
      >
      <template #default>
        <el-form ref="addServiseEnterprise" :model="add_form_data" :rules="rules">
          <el-form-item prop="name" label="名称">
            <el-input
              v-model="add_form_data.name"
              show-word-limit
              maxlength="30"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
          <div class="tr m_top10">
            <el-button @click="resetForm(addServiseEnterprise)">取消</el-button>
            <el-button
              type="primary"
              :loading="btn_loading"
              @click="submit(addServiseEnterprise)"
              >确定</el-button
            >
          </div>
        </el-form>
      </template>
    </el-drawer>
    <el-drawer
      v-model="show_node_file_box"
      direction="rtl"
      size="60%"
      destroy-on-close
      :close-on-click-modal="false"
    >
      <template #title><h4>节点文件配置</h4></template>
      <template #default>
        <el-table :data="node_file_list" border :loading="loading" class="tc">
          <el-table-column label="节点名称" width="150">
            <template #default="scope">
              <span v-for="item in type_list">
                <span v-if="item.type == scope.row.type">{{ item.nodeName }}</span></span
              >
            </template>
          </el-table-column>
          <el-table-column label="按钮名称" width="150">
            <template #default="scope">
              {{ scope.row.buttonName }}
            </template>
          </el-table-column>
          <el-table-column label="节点资料">
            <template #default="scope">
              <el-select v-model="scope.row.fileConfigId" style="width: 400px" multiple>
                <el-option
                  v-for="item in file_list"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button
                :loading="scope.row.btn_loading"
                @click="
                  edit_node_file_list({
                    item: scope.row,
                    type: 1,
                    index: scope.$index,
                  })
                "
              >
                <span v-show="scope.row.id == ''">保存</span>
                <span v-show="scope.row.id != ''">更新</span>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </el-drawer>
    <el-drawer
      v-model="show_file_template_box"
      direction="rtl"
      size="60%"
      destroy-on-close
      :close-on-click-modal="false"
    >
      <template #title><h4>资料模板配置</h4></template>
      <template #default>
        <div
          v-for="(item, index) in file_template_list"
          :key="item.fileConfigId"
          class="m_top20"
        >
          <div>
            {{ file_list[index].name }} (数量：{{ item.limit }} )、(格式：{{
              file_list[index].fileTypeList
            }}
            )、(大小：
            <span v-if="item.minSize <= 0 && item.maxSize <= 0">不限</span>
            <span v-if="item.minSize <= 0 && item.maxSize > 0">
              小于 {{ item.maxSize }} M</span
            >
            <span v-if="item.minSize > 0 && item.maxSize > 0"
              >{{ item.minSize }} M - {{ item.maxSize }} M</span
            >
            )
          </div>
          <upload
            :imageUrl="item.url"
            :width="100"
            :height="100"
            :limit="item.limit"
            :minSize="item.minSize"
            :maxSize="item.maxSize"
            :accept="item.accept"
            :fileNames="item.fileNames"
          ></upload>
          <el-button type="primary" @click="file_template_submit(item)">保存</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { check_role, handle_search_key } from "@/utils/check_role"; // 权限校验
import search from "@/view/components/search.vue";
import setTable from "@/view/components/setTable.vue";
import upload from "@/view/components/upload.vue";
import { onMounted, ref, onUnmounted } from "vue";
import axios from "@/service/HttpRequest";
import serviceApi from "@/service/api";
import EventBus from "@/utils/EventBus";
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
import { useStore } from "vuex";
const store = useStore();
const list = ref();
const show_box = ref();
const addServiseEnterprise = ref<FormInstance>();
const type_list = ref();
const get_node_list = () => {
  axios
    .request({
      url: serviceApi.nodeConfig + "/list",
      method: "post",
      data: handle_search_key({
        enterpriseId: store.state.enterprise_id,
        status: true,
      }),
    })
    .then((res) => {
      console.log(res);
      res.data.forEach((i, index) => {
        i.label = i.nodeName;
        i.value = index + 1;
      });
      type_list.value = res.data;
      console.log(type_list.value);
    })
    .catch((err) => {
      ElMessage.error(err);
    });
};
const add_form_data = ref({
  id: "",
  name: "",
});
// 上传校验规则
const rules = ref({
  name: [{ required: true, message: "请输入名称", trigger: "blur" }],
  buttonName: [{ required: true, message: "请输入按钮名称", trigger: "blur" }],
  nodeName: [{ required: true, message: "请输入节点名称", trigger: "blur" }],
});
const btn_loading = ref(false);
const max_height = ref();
const loading = ref(false);
const height_size = ref(1);
const header_list = ref<any>([
  {
    label: "企业名称",
    value: "",
    showTable: true,
    type: "input",
    isShow: true,
    options: [],
  },
]);

onMounted(() => {
  max_height.value = window.innerHeight - 320; // 带分页的 table 高度
  EventBus.on("refresh", () => {
    get_list();
    ElMessage.success("刷新成功！");
  });
  get_list();
  get_file_list();
  get_node_list();
});
onUnmounted(() => {
  EventBus.off("refresh");
});
const show_node_file_box = ref(false);
const node_file_list = ref([]);
const edit_node_file_list = (e) => {
  if ([1, 2].includes(e.type)) {
    if (e.item.btn_loading) return;
    e.item.btn_loading = true;
    let data = JSON.parse(JSON.stringify(e.item));
    data.fileConfigId = data.fileConfigId.toString();
    axios
      .request({
        url: serviceApi.nodeConfig + (data.id == "" ? "/file" : "/file/" + data.id),
        method: data.id == "" ? "post" : "put",
        data: data,
      })
      .then(() => {
        ElMessage.success("操作成功！");
        setTimeout(() => {
          e.item.btn_loading = false;
          get_node_file_list(serviceEnterpriseId.value);
        }, 1000);
      })
      .catch((err) => {
        e.item.btn_loading = false;
        ElMessage.error(err);
      });
  } else if (e.type == 3) {
    if (e.item.id == "") {
      node_file_list.value = node_file_list.value.filter((i) => {
        return i.id != "";
      });
    } else {
      ElMessageBox.confirm("确定删除该记录？", "", {
        closeOnClickModal: false,
        type: "warning",
      })
        .then(() => {
          axios
            .request({
              url: serviceApi.nodeConfig + "/file/" + e.item.id,
              method: "delete",
            })
            .then(() => {
              ElMessage.success("操作成功！");
              node_file_list.value = node_file_list.value.filter((i) => {
                return i.id == e.item.id;
              });
            })
            .catch((err) => {
              ElMessage.error(err);
            });
        })
        .catch(() => {});
    }
  }
};
const file_template_submit = (e) => {
  console.log(e);
  let data = JSON.parse(JSON.stringify(e));
  data.url = data.url.toString();
  data.fileName = data.fileNames.toString();
  axios
    .request({
      url: serviceApi.serviceEnterprise_fileConfigTemplate,
      method: "post",
      data: data,
    })
    .then(() => {
      ElMessage.success("操作成功！");
    })
    .catch((err) => {
      ElMessage.error(err);
    });
};
const show_file_template_box = ref(false);
// 模板文件
const file_template_list = ref([]);
const get_node_file_template_list = (e) => {
  if (!file_list.value.length) {
    ElMessage.warning("请优先配置项目资料");
    return;
  }
  console.log(e);
  axios
    .request({
      url: serviceApi.serviceEnterprise_fileConfigTemplate + "/list",
      method: "post",
      data: { enterpriseId: store.state.enterprise_id, serviceEnterpriseId: e },
    })
    .then((res) => {
      file_list.value.forEach((i) => {
        i.fileConfigId = i.id;
        i.accept = i.fileTypeList;
        i.limit = i.maxFileNum;
        i.url = [];
        i.fileNames = [];
        i.serviceEnterpriseId = e;
        res.data.forEach((ii) => {
          if (ii.fileConfigId == i.id && ii.url != "") {
            i.url.push(ii.url);
            i.fileNames.push(ii.fileName);
          }
        });
      });
      console.log(file_list.value);
      file_template_list.value = file_list.value;
      show_file_template_box.value = true;
    })
    .catch((err) => {
      ElMessage.error(err);
    });
};
const serviceEnterpriseId = ref("");
const get_node_file_list = (e) => {
  if (!file_list.value.length) {
    ElMessage.warning("请优先配置项目资料");
    return;
  }
  show_node_file_box.value = true;
  loading.value = true;
  axios
    .request({
      url: serviceApi.nodeConfig + "/file/list",
      method: "post",
      data: {
        serviceEnterpriseId: serviceEnterpriseId.value,
      },
    })
    .then((res) => {
      type_list.value.forEach((i, index) => {
        let has_type = res.data.some((ii) => {
          return ii.nodeId == i.id && i.status;
        });
        if (!has_type) {
          res.data.push({
            id: "",
            fileConfigId: [],
            serviceEnterpriseId: e,
            type: i.type,
            nodeId: i.id,
            stopNodeType: index == 0 ? "1" : "4",
            buttonName: "",
          });
        } else {
          res.data[index].fileConfigId =
            res.data[index].fileConfigId == ""
              ? []
              : res.data[index].fileConfigId.split(",");
        }
      });
      console.log(type_list.value, res.data);
      node_file_list.value = res.data;
      loading.value = false;
    })
    .catch((err) => {
      ElMessage.error(err);
      loading.value = false;
    });
};
const submit = async (formEl: FormInstance | undefined) => {
  await formEl.validate((valid) => {
    if (valid) {
      if (btn_loading.value) return;
      btn_loading.value = true;
      axios
        .request({
          url: serviceApi.serviceEnterprise_curd,
          method: "post",
          data: add_form_data.value,
        })
        .then(() => {
          ElMessage.success("操作成功！");
          setTimeout(() => {
            resetForm(formEl);
            get_list();
          }, 1000);
        })
        .catch((err) => {
          btn_loading.value = false;
          ElMessage.error(err);
        });
    }
  });
};
const table_list = ref([]);
const get_list = () => {
  loading.value = true;
  axios
    .request({
      url: serviceApi.serviceEnterpriseList,
      method: "post",
    })
    .then((res) => {
      console.log(res);
      list.value = res.data === null ? [] : res.data;
      table_list.value = res.data === null ? [] : res.data;
      loading.value = false;
    })
    .catch((err) => {
      ElMessage.error(err);
      loading.value = false;
    });
};
const file_list = ref([]);
const get_file_list = () => {
  axios
    .request({
      url: serviceApi.projectInformation + "/list",
      method: "post",
      data: handle_search_key({ enterpriseId: store.state.enterprise_id }),
    })
    .then((res) => {
      console.log(res);
      file_list.value = res.data;
    })
    .catch((err) => {
      ElMessage.error(err);
    });
};
const search_key = () => {
  table_list.value = list.value.filter((i) => {
    return i.name.includes(header_list.value[0].value);
  });
};
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  add_form_data.value = {
    id: "",
    name: "",
  };
  btn_loading.value = false;
  show_node_file_box.value = false;
  show_box.value = false;
};
</script>

<style lang="scss" scoped>
.top_item {
  border: 1px solid #ccc;
  cursor: pointer;
  padding: 5px;
  border-radius: 5px;
  display: flex;
  align-items: center;
  &:hover {
    color: #3580eb;
    border-color: #3580eb;
  }
}
.line {
  background-color: #333;
  width: 1px;
  height: 16px;
  margin: 0 10px;
}
</style>
